<?php

namespace App\Http\Controllers;

use App\Models\Lists;
use App\Models\Users;
use Illuminate\Http\Request;
use App\Http\Lib\Validator;
use App\Http\Lib\ResBase;
use Illuminate\Support\Str;
use function PHPUnit\Framework\isEmpty;
use function PHPUnit\Framework\isFalse;
use Illuminate\Support\Facades\DB;

class ListController extends Controller
{
    //添加目录
    public function addlist(Request $request){
        $data = $request->all();
        $parentId = $request->has('parentId') ? $data['parentId'] : "0";
        $listname = $data['listname'];
        $v = Validator::useValidator($data,['listname'=>'required']);
        $root = $request->file('root');  //权限
        if($v->fails()){
            return ResBase::ApiRes(401,'文件名不能为空','failed');
        }
        if($parentId === '0'){
            $p = Lists::create([
                'id'=>Str::random(5),
                'name'=>$listname,
                'parent_id'=> '0',
                'has_children'=>false,
                'root'=>$root
            ]);
            if(empty($p)){
                return ResBase::ApiRes(400,'添加失败','failed');
            } else {
                return ResBase::ApiRes(200,['list_id'=>$p->id,'list_name'=>$p->name,'children'=>$p->has_children,'parentId'=>$parentId],'success');
            }
        } else {
            $r = Lists::where('id',$parentId)->first();
            if(!$r){
                return ResBase::ApiRes(402,'当前目录无效，无法创建文件夹','failed');
            } else {
                //父节点的has_children改为true
                try {
                    $r->has_children = true;
                    $r->save();
                } catch (\Exception $e){
                    return ResBase::ApiRes(400,$e->getMessage(),'failed');
                }
                //创建数据
                $res = Lists::create([
                    'id'=>Str::random(5),
                    'name'=>$listname,
                    'parent_id'=> $parentId,
                    'has_children'=>false
                ]);
                if(empty($res)){
                    return ResBase::ApiRes(400,'添加失败','failed');
                } else {
                    return ResBase::ApiRes(200,['list_id'=>$res->id,'list_name'=>$res->name,'children'=>$res->has_children,'parentId'=>$parentId],'success');
                }
            }
        }
    }

    //删除目录
    public function dellist(Request $request){
        $id = $request->input('listId');
        self::del($id);
        //根据兄弟节点判断是否修改has_children
//        if($id !== '0'){
//            //目标节点
//            $tar = Lists::find($id);
////            //兄弟节点个数
////            $c = Lists::where('parent_id',$tar['parent_id'])->count();
////            if(!empty($c) && $c === 1){
////                Lists::find($tar->parent_id)->update(['has_children' => false]);
////            }
//        }
    }


    //修改目录名
    public function editlist(Request $request){
        $data = $request->all();
        $id = $request->input('listId');
        $newname = $request->input('newListName');
        $v = Validator::useValidator($data,[
            'listId' => 'required',
            'newListName' => 'required',
        ]);
        if($v ->fails()){
            return ResBase::ApiRes(403,'数据格式校验失败','failed');
        }

        $tar = Lists::find($id);
        if(empty($tar)){
            return ResBase::ApiRes(404,'无效文件夹','failed');
        }

        $res = $tar->update(['name' => $newname]);
        if(!$res){
            return ResBase::ApiRes(400,'更新失败','failed');
        } else {
            return ResBase::ApiRes(200,'更新成功');
        }
    }


    //获取列表
//    public function getlist($id = '0'){
//        $listArr = [];
//        $lists = Lists::where('parent_id', $id)->get();
//
//        foreach ($lists as $i) {
//            $children = self::getlist($i->id); // 递归调用，获取子节点
//            array_push($listArr, [
//                'listId' => $i->id,
//                'parent_id' => $i->parent_id,
//                'children' => $children,
//                'fileName'=> $i->name,
//                'root'=>3
//            ]);
//        }
//
//        return $listArr;
//    }
    public function getlist(Request $request, $id = '0', $root = null){
        $listArr = [];
        $userid = $request->input('userId');

        if ($root === null) {
            $r = Users::where('user_id', $userid)->first();  //权限
            $root = $r->root;  //权限
//            dd($r->root);
        }

        $lists = Lists::where('parent_id', $id)
            ->where('root', '>=', $root)
            ->get();
        foreach ($lists as $i) {
            $children = self::getlist($request, $i->id, $root); // 递归调用，传递用户权限
//            var_dump($listArr);
            array_push($listArr, [
                'listId' => $i->id,
                'parent_id' => $i->parent_id,
                'children' => $children,
                'fileName' => $i->name
            ]);
        }

//        dd($listArr);
        return $listArr;
    }



    public static  function del($id)
    {
        $list = Lists::find($id); //当前节点
        $r = $list->delete();
        if (!$list) {
            return ResBase::ApiRes(401,'目录不存在或已被删除','failed');
        }
        $fn = Lists::where('parent_id',$id)->get();
        $c = $fn->count();
        if($c>=1){ //子节点不为0
            foreach ($fn as $item){
                if($item->has_children){
                    self::del($item->id);
                } else {
                    $r2 = $item->delete();
                    $item->delete();
                    if($r2 && $r){
                        return ResBase::ApiRes(200,'删除成功');
                    } else {
                        return ResBase::ApiRes(400,'删除失败','failed');
                    }
                }
            }
        } else {
            $r =  Lists::where('parent_id',$id)->delete();
            if(!$r){
                return ResBase::ApiRes(400,'删除失败','failed');
            }
        }
    }
}

